package simulator;

import XMLLoader.task.Task;
import org.junit.Test;
import resousce.Cluster;
import resousce.DMA;
import resousce.DSP;
import resousce.ResourcesManager;
import scheduleAlgorithm.FIFO;
import scheduleManager.TaskManager;
import timeCnter.myTime;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class main {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        LinkedList<Task> globalTaskList = TaskManager.getGlobalTaskList();

        long begin = System.currentTimeMillis();


        for (Task t :globalTaskList) {
            threadPool.execute(t);
        }

        ResourcesManager resourcesManager = ResourcesManager.getResourcesManager();

        threadPool.execute(resourcesManager);
        threadPool.execute(FIFO.getInstance());

        //start all resources
        List<Thread> components = resourcesManager.getComponents();
        for(Thread thread:components){
            threadPool.execute(thread);
        }

        while(!allTaskFinish()){
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        int simulateTime = (int) (System.currentTimeMillis() - begin);

        for(Cluster cluster :resourcesManager.getClusterList()){
            List<DSP> dspList = cluster.getDspList();
            for(DSP d : dspList){
//                System.out.println(d.getDspId() + ":空闲时间" + (myTime.getTime() - d.getActiveTime()) + ",执行时间：" +d.getActiveTime());
                double utilization = (double)(simulateTime - d.getNewIdleTime())/simulateTime;
                System.out.println(d.getDspId() + ":执行时间" + (simulateTime - d.getNewIdleTime()) + ",空闲时间：" +d.getNewIdleTime());
                System.out.println("使用率：" + utilization);
            }
            for(DMA d : cluster.getDmaList()){
                System.out.println("DMA:" + d.getDmaId() + ":空闲时间" + (myTime.getTime() - d.getActiveTime()) + " shu,执行时间：" +d.getActiveTime());
            }
        }

        System.out.println(simulateTime);

        threadPool.shutdownNow();




    }

    static private boolean allTaskFinish(){
        LinkedList<Task> globalTaskList = TaskManager.getGlobalTaskList();
        for(Task t:globalTaskList){
            if(!t.ifFinish())return false;
        }
        return true;
    }


    @Test
    public void test01(){
//        double utilization = (double)124234/324234;
//        System.out.println("使用率" + utilization);
    }
}
